// 当前只使用 1.8.5 版本
import Schema from "async-validator";

export function registerAll() {
  Schema.register("dynamicNumber", dynamicNumber);
}

/**
 * const rules = createNumberRules({
 *   type: "integer",
 *   typeMessage: "数量值必须是整数",
 *   min: 0,
 *   minMessage: "数量不能小于0",
 *   max: () => someValue,
 *   maxMessage: "数量不能大于那个值"
 * });
 */
export function createNumberRules(options = {}) {
  const rules = [];
  // 默认 required
  if (options.required !== false) {
    rules.push({
      required: true,
      message: options.requireMessage || "字段不能为空",
      trigger: "blur"
    });
  }
  if (options.type === "integer") {
    rules.push({
      type: "integer",
      message: options.typeMessage || "值必须是整数",
      trigger: ["change", "blur"]
    });
  } else {
    rules.push({
      type: "number",
      message: options.typeMessage || "值必须是数字",
      trigger: "blur"
    });
  }
  if (options.min != null) {
    rules.push({
      type: "dynamicNumber",
      min: options.min,
      message: options.minMessage,
      trigger: ["change", "blur"]
    });
  }
  if (options.max != null) {
    rules.push({
      type: "dynamicNumber",
      max: options.max,
      message: options.maxMessage,
      trigger: ["change", "blur"]
    });
  }
  return rules;
}

export function createStringRules(options = {}) {
  const rules = [];
  // 默认 required
  if (options.required !== false) {
    rules.push({
      required: true,
      message: options.requireMessage || "字段不能为空",
      trigger: "blur"
    });
  }
  if (options.min != null) {
    rules.push({
      type: "string",
      min: options.min,
      message: options.minMessage || `长度不能小于 ${options.min}`,
      trigger: "blur"
    });
  }
  if (options.max != null) {
    rules.push({
      type: "string",
      max: options.max,
      message: options.maxMessage || `长度不能大于 ${options.max}`,
      trigger: ["blur", "change"]
    });
  }
  return rules;
}

/**
 * 动态校验最大最小值
 * { type: "dynamicNumber", min: () => someValue, message: "值你太小" }
 */
const dynamicNumber = function(rule, value, callback, _source, _options) {
  const errors = [];
  const v = typeof value === "number" ? value : Number.parseFloat(value);
  if (rule.min != null) {
    if (typeof rule.min === "number") {
      if (v < rule.min) {
        errors.push("值不能小于" + rule.min);
      }
    } else if (typeof rule.min === "function") {
      const r = rule.min();
      if (typeof r === "number" && v < r) {
        errors.push("值不能小于" + r);
      }
    }
  }
  if (rule.max != null) {
    if (typeof rule.max === "number") {
      if (v > rule.max) {
        errors.push("值不能大于" + rule.max);
      }
    } else if (typeof rule.max === "function") {
      const r = rule.max();
      if (typeof r === "number" && v > r) {
        errors.push("值不能大于" + r);
      }
    }
  }
  callback(errors);
};
